//
//  UserInfoDataProvider.m
//  PigMarket
//
//  Created by Felix on 2019/4/12.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "UserInfoDataProvider.h"

#import "TokenCacheManager.h"

// 沙盒路径
#define UserInfoPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"userInfo"]

@implementation UserInfoDataProvider

@synthesize userInfo = _userInfo;


+ (UserInfoDataProvider *)sharedInstance {
    static UserInfoDataProvider *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[UserInfoDataProvider alloc] init];
    });
    return instance;
}


- (void)setUserInfo:(UserInfo *)userInfo {
    _userInfo = userInfo;
    if (userInfo) {
        [NSKeyedArchiver archiveRootObject:userInfo toFile:UserInfoPath];
    } else {
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        if ([defaultManager isDeletableFileAtPath:UserInfoPath]) {
            [defaultManager removeItemAtPath:UserInfoPath error:nil];
        }
    }
}


-(UserInfo *)userInfo {
    if (!_userInfo) {
        _userInfo = [NSKeyedUnarchiver unarchiveObjectWithFile:UserInfoPath];
    }
    return _userInfo;
}


- (void)logoutPersonal {
    // 清除token
    [TokenCacheManager sharedInstance].memberToken = nil;
    if (_userInfo) {
        _userInfo.isLogin = NO;
        _userInfo.isIMLogin = NO;
        self.userInfo = _userInfo;
    }
}

@end
